﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Interfaces;
using Sharp.Infrastructure.IoC;
using Sharp.ServiceContracts;

namespace Sharp.Application
{
    /// <summary>
    ///     对应用层服务进行初始化。
    /// </summary>
    /// <remarks>
    ///     包含的初始化任务有：
    ///     1. AutoMapper框架的初始化
    /// </remarks>
    public class Bootstraper : IBootstrapPlugin
    {
        public void Initialize()
        {
            var dllFiles = Directory.GetFiles(System.Environment.CurrentDirectory + @"\bin\",
                "*.dll");

            #region 初始化AutoMapper
            List<Profile> list = new List<Profile>();

            foreach (var file in dllFiles)
            {
                if (!file.Contains("Application")) continue;

                byte[] fileData = File.ReadAllBytes(file);
                var assembly = Assembly.Load(fileData);
                foreach (var type in assembly.GetTypes())
                {
                    if (type.IsAbstract || type.IsInterface)
                    {
                        continue;
                    }
                    if (typeof(Profile).IsAssignableFrom(type))
                    {
                        list.Add(Activator.CreateInstance(type) as Profile);
                    }
                }
            }

            Mapper.Initialize(x =>
            {
                list.ForEach(x.AddProfile);
            });
            #endregion



            this.IsAlready = true;
        }

        public bool IsAlready { get; set; }
    }
}